<template>
  <el-row>
    <el-col :key="index" v-for="(item, index) in tableList" :span="24">
      <el-row>
        <el-col :span="24">
          <Portlet :title="item.name">
            <el-form ref="searchForm" class="el-form-s el-form-col" :model="item.search"
                     label-position="left">
              <el-row :gutter="15">
                <el-col :span="6" :key="itemIndex" v-for="(searchItem, itemIndex) in getSearchData(item)">

                  <el-form-item label-width="110px" :label="searchItem.subject + ':'"
                                v-if="['radio', 'checkBox'].indexOf(searchItem.type) >= 0" :prop="searchItem.sqlName">
                    <!-- 单选 -->
                    <el-radio-group v-if="searchItem.type == 'radio'" v-model="item.search[searchItem.sqlName]">
                      <el-radio
                        v-for="op in getElOptions(searchItem)"
                        :key="op.value"
                        :label="op.value"
                      >{{ op.name }}
                      </el-radio>
                    </el-radio-group>

                    <!-- 多选 -->
                    <el-checkbox-group v-if="searchItem.type == 'checkBox'" v-model="item.search[searchItem.sqlName]">
                      <el-checkbox
                        v-for="op in getElOptions(searchItem)"
                        :key="op.value"
                        :label="op.value"
                      >{{ op.name }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>

                  <el-form-item v-else :prop="searchItem.sqlName">

                    <!-- 下拉 -->
                    <el-select v-if="searchItem.type == 'select'" v-model="item.search[searchItem.sqlName]"
                               :placeholder="searchItem.subject">
                      <el-option v-for="op in getElOptions(searchItem)"
                                 :key="op.value"
                                 :label="op.name"
                                 :value="op.value">
                      </el-option>
                    </el-select>

                    <!-- 多选下拉 -->
                    <el-select v-if="searchItem.type == 'select_checkbox'" multiple
                               v-model="item.search[searchItem.sqlName]" :placeholder="searchItem.subject">
                      <el-option v-for="op in getElOptions(searchItem)"
                                 :key="op.value"
                                 :label="op.name"
                                 :value="op.value">
                      </el-option>
                    </el-select>

                    <!-- 输入 -->
                    <el-input v-if="searchItem.type == 'input'" v-model="item.search[searchItem.sqlName]"
                              :placeholder="searchItem.subject">
                    </el-input>

                    <!-- 日期 -->
                    <el-date-picker v-if="searchItem.type == 'date'" type="date"
                                    v-model="item.search[searchItem.sqlName]"
                                    :placeholder="searchItem.subject">
                    </el-date-picker>

                    <!-- 日期（年月） -->
                    <el-date-picker v-if="searchItem.type == 'date-month'" type="month"
                                    v-model="item.search[searchItem.sqlName]" :placeholder="searchItem.subject">
                    </el-date-picker>

                  </el-form-item>

                </el-col>

                <el-col :span="6" style="min-width: 260px">
                  <el-button :loading="loading" plain native-type="submit" type="primary" @click.prevent="searchTable(item, $event)">
                    {{ searchText }}
                  </el-button>
                    <el-button @click.prevent="resetTable(index, $event)">重置</el-button>

                    <el-button v-if="item.url" type="info" @click.prevent="downloadExcel(item, $event)">下载</el-button>
                </el-col>

              </el-row>
            </el-form>
          </Portlet>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <Portlet>
            <el-table
              :data="item.tbody || []"
              v-loading="loading"
            >

              <el-table-column align="center" fixed="left" type="index">
              </el-table-column>
              <elTableColumnHead :thead="item.thead || []"></elTableColumnHead>
            </el-table>

            <div class="pagination-container pull-right">
              <Pagination
                :totalItem="getTotalItem(item)"
                :perItem="item.pageSize"
                @pagination="(page) => { pagination(page, item) }"
                @sizeChange="(size) => { sizeChange(size, item) }"
              />
            </div>
          </Portlet>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>
<script>
import {dotData, alert, merge, copy, param} from '@/utils'
import moment from 'moment'
import lodash from 'lodash'
import elTableColumnHead from './elTableColumnHead'

export default {
  name: 'reportIndex',
  components: {
    elTableColumnHead
  },
  data() {
    return {
      params: {
        formsId: this.$route.params.id
      },
      tableList: [],
      search: {},
      datasTable: null,
      loading: false,
      searchText: '搜索',
      gateway: this.$route.query.gateway
    }
  },
  computed: {
    trueGateway() {
      if (this.gateway) {
        return lodash.trim(lodash.trim(this.gateway), '/')
      }
      return 'ms-forms'
    }
  },
  mounted() {
    this.$ajax.get(`/${this.trueGateway}/forms/forms-id`, this.params).then(response => {
      const success = response.success
      if (success) {
        const data = response.data
        if (Array.isArray(data)) {
          let tempArr = data
          tempArr.forEach(v => {
            // 处理搜索
            this.handleSearch(v)
          })
          this.tableList = tempArr
        } else {
          alert('报表系统获取的不是一个数组')
        }
      }
      return this.tableList
    }).then(_ => {
      this.tableList.forEach(item => {
        if (item.query === '1') { // 1(页面刷新自动查询数据)，0（手动触发）
          this.searchTable(item)
        }
      })
      return ''
    })
  },
  methods: {
    // 给最上面一行添加列合并数
    addPreRowColRowSpan(arr, rowIndex, itemIndex) {
      let obj = dotData(arr, `[${rowIndex}][${itemIndex}]`)
      if (!obj) {
        return
      }
      if (dotData(obj, 'show')) {
        obj['rowspan']++
      } else {
        this.addPreRowColRowSpan(arr, rowIndex - 1, itemIndex)
      }
    },
    // 获取分页总数
    getTotalItem(item) {
      return item.count || 0
    },
    // 分页
    pagination(page, item) {
      let itemParams = dotData(item, 'itemParams') || {}
      itemParams.pageNum = page
      this.$set(item, 'itemParams', itemParams)
      this.httpGetData(item)
    },
    // 重新获取编号
    httpGetData(item) {
      let params = dotData(item, 'itemParams') || {}
      // 格式化一下请求参数
      for (let k in params) {
        if (Array.isArray(params[k])) {
          params[k] = JSON.stringify(params[k])
        }
      }
      if (!params.pageNum) {
        params.pageNum = 1
      }
      if (!params.pageSize) {
        params.pageSize = 20
      }
      const tableId = dotData(item, 'id')
      if (!tableId) {
        alert('item 下的id（tableId）未获取')
        return
      }
      params.tableId = tableId
      // 清空一下表格
      this.loading = true
      this.searchText = '加载中'
      this.$ajax.table(`/${this.trueGateway}/forms/forms-data`, params).then(response => {
        const tbody = dotData(response, 'data')
        if (Array.isArray(tbody)) {
          this.$set(item, 'tbody', tbody)
        }
        const totalItem = dotData(response, 'totalItem')
        if (totalItem || String(totalItem) === '0') {
          this.$set(item, 'count', parseInt(totalItem))
        }
        return response
      }).finally(_ => {
        this.loading = false
        this.searchText = '搜索'
      })
    },
    // 页面大小
    sizeChange(size, item) {
      let itemParams = dotData(item, 'itemParams') || {}
      itemParams.pageSize = size
      this.$set(item, 'itemParams', itemParams)
      this.httpGetData(item)
    },
    // 处理搜索
    handleSearch(item) {
      let tempArr = this.getSearchData(item)
      if (tempArr.length > 0) {
        this.$set(item, 'search', {})
        tempArr.forEach(v => {
          if (v.sqlName) {
            let defaultValue = v.defaultValue || ''
            if (v.type === 'date') {
              if (lodash.endsWith(v.sqlName, 'CUSTOM_MY_START')) {
                defaultValue = v.defaultStart
              }
              if (lodash.endsWith(v.sqlName, 'CUSTOM_MY_END')) {
                defaultValue = v.defaultEnd
              }
            }
            // 数组类型转化为数组
            if (v.type === 'checkBox' || v.type === 'select_checkbox') {
              if (v.defaultValue) {
                try {
                  v.defaultValue = JSON.parse(v.defaultValue)
                } catch (e) {
                  console.error(e)
                }
              }
              defaultValue = v.defaultValue || []
            }
            this.$set(item.search, v.sqlName, defaultValue)
          }
        })
      }
    },
    // 获取搜索条件
    getSearchData(item) {
      let queryConditon = dotData(item, 'queryConditon')
      if (Array.isArray(queryConditon)) {
        return queryConditon
      }
      return []
    },
    // 获取el 下的options
    getElOptions(searchItem) {
      return Array.isArray(dotData(searchItem, 'items')) ? dotData(searchItem, 'items') : []
    },
    // 搜索
    searchTable(item, event) {
      let itemParams = {}
      if (dotData(item, 'pageSize')) {
        itemParams.pageSize = dotData(item, 'pageSize')
      }
      let search = copy(dotData(item, 'search'), true)
      itemParams = merge(itemParams, search)
      for (let k in itemParams) {
        if (moment.isDate(itemParams[k])) {
          itemParams[k] = moment(itemParams[k]).format('YYYY-MM-DD')
        }
      }
      this.$set(item, 'itemParams', itemParams)
      this.httpGetData(item)
    },
    // 重置表格
    resetTable(index, $event) {
      let dom = this.$refs['searchForm']
      if (Array.isArray(dom)) {
        dom = dom[index]
      }
      dom.resetFields()
    },
    // 下载excel
    downloadExcel(item, event) {
      let params = dotData(item, 'itemParams') || {}
      const tableId = dotData(item, 'id')
      params.tableId = tableId
      delete params.pageSize
      let href = '/api' + item.url + '?' + param(params)
      window.location.href = href
    }
  }
}
</script>
